export const setCookie = (name, value, Days) => {
	var exp = new Date();
	exp.setTime(exp.getTime() + Days * 24 * 60 * 60 * 1000);
	document.cookie = name + "=" + escape(value) + ";expires=" + exp.toGMTString();
}

export const getCookie = (key) => {
	var arr, reg = RegExp('(^| )' + key + '=([^;]+)(;|$)');
	if (document.cookie.match(reg)) {
		arr = document.cookie.match(reg)
		return decodeURIComponent(arr[2]);
	}
	else {
		return null;
	}
}


export const delCookie = (key) => {
	// 删除cookie
	var date = new Date();
	date.setTime(date.getTime() - 1);
	var delValue = getCookie(key);
	if (delValue != null) {
		document.cookie = key + '=' + delValue + ';expires=' + date.toGMTString();
	}
}

//防抖
export const debounce = (func, wait, immediate) => {
	let timeout;
	return function () {
		let context = this;
		let args = arguments;

		if (timeout) clearTimeout(timeout);
		if (immediate) {
			var callNow = !timeout;
			timeout = setTimeout(() => {
				timeout = null;
			}, wait)
			if (callNow) func.apply(context, args)
		}
		else {
			timeout = setTimeout(function () {
				func.apply(context, args)
			}, wait);
		}
	}
}

//节流
export const throttle = (func, wait) => {
	let previous = 0;
	return function () {
		let now = Date.now();
		let context = this;
		let args = arguments;
		if (now - previous > wait) {
			func.apply(context, args);
			previous = now;
		}
	}
}



export const scroll = (ele) => {
	const scrollPart = document.querySelector(ele); // 目标节点的id或class
	const top = scrollPart.getBoundingClientRect().top - 50;
	const pageY = window.pageYOffset;
	const endPosition = top + pageY;

	const startTime = +new Date();
	const duration = 500; //ms

	function run() {
		const time = +new Date() - startTime;

		window.scrollTo(0, pageY + top * (time / duration));
		run.timer = requestAnimationFrame(run);

		if (time >= duration) {
			window.scrollTo(0, endPosition);
			cancelAnimationFrame(run.timer);
		}
	}
	requestAnimationFrame(run);
}
